package smecta.client.print.controller;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import smecta.client.print.util.AlertUtil;
import smecta.client.print.util.AuthUtil;
import smecta.client.print.util.MachineCodeUtil;

@Slf4j
@Component
public class LicenseController {

    @FXML
    private TextField machineCodeField;

    @FXML
    private TextField authCodeField;

    @FXML
    public void initialize() {
        // 设置machineCodeField的默认值为机器的IP地址，并设置为不可编辑
        machineCodeField.setText(MachineCodeUtil.generateMachineCode());
        machineCodeField.setEditable(false);
        authCodeField.setEditable(true);
    }

    @FXML
    protected void handleCopy(ActionEvent event) {
        String text = machineCodeField.getText();
        Clipboard clipboard = Clipboard.getSystemClipboard();
        ClipboardContent content = new ClipboardContent();
        content.putString(text);
        clipboard.setContent(content);
        AlertUtil.info("授权码已复制到剪贴板");
    }

    @FXML
    protected void handleActivate(ActionEvent event) {
        // 获取用户输入的授权码
        String authCode = authCodeField.getText();
        // 进行激活逻辑处理，例如验证授权码
        if (authCode != null && !authCode.isEmpty()) {
            try{
                AuthUtil.saveAuthCode(authCode);
                if (AuthUtil.check()) {
                    AlertUtil.info("授权码验证成功，激活完成，请退出系统后重新登录!");
                } else {
                    AlertUtil.error("激活失败！");
                }
            }catch (Exception e){
                log.error("handleActivate error:{}", e);
                AlertUtil.error("激活异常！");
            }
        } else {
            // 授权码为空，提示用户
            AlertUtil.error("授权码不能为空，请重新输入！");
        }
    }
}